package com.demo.serviceimpl;

import com.demo.bean.Lesson;
import com.demo.mapper.LessonMapper;
import com.demo.service.AnalysisHtmlService;
import com.demo.service.ExecutePythonService;
import com.demo.service.LessonSaveService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 李天航
 * lesson操作
 */
@Service
public class LessonSaveImpl implements LessonSaveService {

    @Resource
    LessonMapper lessonMapper;
    @Resource
    AnalysisHtmlService analysisHtmlService;
    @Resource
    ExecutePythonService executePythonService;



    boolean judgeConflict(List<Lesson> lessons,Lesson rawLesson){
        int l,r;
        l=0;r=lessons.size()-1;
        while(l<r){
            int mid=l+r+1>>1;
            if(lessons.get(mid).getBeginTime()<=rawLesson.getBeginTime()){
                l=mid;
            }else {
                r=mid-1;
            }
        }
        if(lessons.get(l).getEndTime()>rawLesson.getBeginTime()) {
            return false;
        }
        l=0;r=lessons.size()-1;
        while(l<r){
            int mid=l+r>>1;
            if(lessons.get(mid).getBeginTime()>=rawLesson.getBeginTime()) r=mid;
            else l=mid+1;
        }
        if(lessons.get(l).getBeginTime()<rawLesson.getEndTime()){
            return false;
        }
        return true;
    }
    /**
     * 将课程批量保存进数据库
     * @param sno 学号
     * @param password 登录教务处的密码
     * @param userAccount 用户账号
     * @return status,msg,lessons
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public LinkedHashMap<String, Object> getLessonsAndSave(String sno, String password, String userAccount) {
        String htmlText=executePythonService.getHtmlByExecutePython(sno,password);
        LinkedHashMap<String, Object> resultMap=new LinkedHashMap<>();
        if(htmlText.length()==0||htmlText==""){
            resultMap.put("status",500);
            resultMap.put("msg","学号或者密码错误");
            return  resultMap;
        }
        List<Lesson> newLessons=analysisHtmlService.getLessonsFromText(htmlText);
        for(Lesson lesson:newLessons){
            lesson.setUserAccount(userAccount);
        }
        lessonMapper.clearLessons(userAccount);
        lessonMapper.addLessons(newLessons);

        resultMap.put("status",200);
        resultMap.put("msg","获得成功");
        resultMap.put("lessons",newLessons);
        return resultMap;
    }
}
